package com.meisiabc.app.service;

import com.google.common.io.Resources;
import com.meisiabc.support.wechat.WechatMpClient;
import com.meisiabc.utils.PictureMerge;
import com.riversoft.weixin.common.event.ClickEvent;
import com.riversoft.weixin.common.media.Media;
import com.riversoft.weixin.common.media.MediaType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;

@Slf4j
@Service
public class MediaService {
    @Autowired
    private WechatMpClient wechatMpClient;
    @Autowired
    private RecommenderService recommenderService;

    @Async
    public void sendRecommenderImg(ClickEvent clickEvent, String mobile) {
        try {
            InputStream inputStream = recommenderService.wechatQrcode(mobile);
            BufferedImage bufferedImage = PictureMerge.merge(Resources.getResource("templates/post.jpg"), inputStream, 435, 1700, 1.0f);
            InputStream input = getImageStream(bufferedImage);
            if (input == null) {
                return;
            }
            Media media = wechatMpClient.uploadMedias(MediaType.image, input, clickEvent.getFromUser() + ".jpg");
            if (media != null) {
                log.info("sendRecommenderImg.MediaId: {}", media.getMediaId());
                wechatMpClient.careMessagesForImage(clickEvent.getFromUser(), media.getMediaId());
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }

    public InputStream getImageStream(BufferedImage bi) {
        InputStream is = null;
        bi.flush();
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        try {
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
            ImageIO.write(bi, "png", imOut);
            is = new ByteArrayInputStream(bs.toByteArray());
        } catch (IOException e) {
            log.error("", e);
        }
        return is;
    }

//    public static void main(String[] args) throws IOException {
//        BufferedImage bufferedImage = PictureMerge.merge(Resources.getResource("templates/post.jpg"), Resources.getResource("templates/qrcode.jpg"), 435, 1700, 1.0f);
//        ImageIO.write(bufferedImage, "png", new File("/Users/sunchp/gitRepo/gitee/meisi/postcon.jpg"));
//    }
}
